// component/image-cropper.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        /**
         * 裁剪框宽度
         */
        width: {
            type: Number,
            value: 200,
        },
        /**
         * 裁剪框高度
         */
        height: {
            type: Number,
            value: 200,
        },
        cut_top: {
            type: Number,
            value: null,
        },
        cut_left: {
            type: Number,
            value: null,
        },
        /**
         * 图片宽度
         */
        img_width: {
            type: null,
            value: null,
        },
        /**
         * 图片高度
         */
        img_height: {
            type: null,
            value: null,
        },
        /**
         * 图片路径
         */
        imgSrc: {
            type: String,
        },
        cut_top: {
            type: Number,
            value: null,
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        info: wx.getSystemInfoSync(),
        INIT_IMGWIDTH: 0, // 图片设置尺寸
        INIT_IMGhEIGHT: 0, // 图片甚至尺寸
        _flag_bright: true, // 背景是否亮
        _canvas_overflow: true, // canvas缩略图是否在屏幕外面
        _canvas_width: 200,
        _canvas_height: 200,

        watch: {
            //  监听截取框宽高变化
            width(value, that) {
                if (value < that.data.min_width) {
                    that.setData({
                        width: that.data.min_width,
                    });
                }
                that._computeCutSize();
            },
            height(value, that) {
                if (value < that.data.min_height) {
                    that.setData({
                        height: that.data.min_height,
                    });
                }
                that._computeCutSize();
            },
            imgSrc(value, that) {
                that.pushImg();
            },
            cut_top(value, that) {
                that._cutDetectionPosition();
            },
        },
    },

    attached() {
        this.data.info = wx.getSystemInfoSync();
<<<<<<< HEAD
        // 启用数据监听
        this._watcher();
        console.log("_watcher之后:  img_width  ", this.data.img_width);
        console.log("_watcher之后:  img_height  ", this.data.img_height);
=======
        console.log('attached--this.data.info:  ', this.data.info)
            // 启用数据监听
        this._watcher();
        console.log('_watcher之后 image_width:  ', this.data.img_width);
>>>>>>> 54642cf13f78c8873f066b94d3f77832c7dc3fe5

        this.data.INIT_IMGWIDTH = this.data.img_width;
        this.data.INIT_IMGHEIGHT = this.data.img_height;
        this.setData({
            _canvas_height: this.data.height,
            _canvas_width: this.data.width,
        });
<<<<<<< HEAD
        console.log("height, _canvas_height", this.data._canvas_height);
        console.log("width, _canvas_width", this.data._canvas_width);
        this._initCanvas();
        this.data.imgSrc && (this.data.imgSrc = this.data.imgSrc);
        // 根据开发者设置的图片目标尺寸计算实际尺寸
        // 设置裁剪框大小>设置图片尺寸>绘制canvas
        this._computeCutSize();
        console.log(
            "_computeCutSize之后",
            this.data.width,
            this.data.height,
            this.data.cut_left,
            this.data.cut_top
        );
=======
        console.log('_canvas_height', this.data._canvas_height);
        console.log('_canvas_width', this.data._canvas_width);
        this._initCanvas()
        this.data.imgSrc && (this.data.imgSrc = this.data.imgSrc)
            // 根据开发者设置的图片目标尺寸计算实际尺寸
        this._initImageSize()
            // 设置裁剪框大小>设置图片尺寸>绘制canvas
        console.log('_computeCutSize之前', this.data.width, this.data.height, this.data.cut_left, this.data.cut_top);
        this._computeCutSize()
        console.log('_computeCutSize之后', this.data.width, this.data.height, this.data.cut_left, this.data.cut_top);
>>>>>>> 54642cf13f78c8873f066b94d3f77832c7dc3fe5

        // 检查裁剪框是否在范围内
        this._cutDetectionPosition();
        console.log(
            "运行_setCutCenter之后 cut_top,cut_left  ",
            this.data.cut_top,
            this.data.cut_left
        );
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 加载(更换)图片
         */
        pushImg(src) {
            if (src) {
                this.setData({
                    imgSrc: src,
                });

                // 发现是手动赋值直接返回，交给watch处理
                return;
            }

            console.log(this.data.imgSrc);

            if (!this.data.imgSrc) return;
            wx.getImageInfo({
                src: this.data.imgSrc,
                success: (res) => {
                    this.data.imageObject = res;
                    // 图片非本地路径需要换成本地路径
                    if (this.data.imgSrc.search(/tmp/) == -1) {
                        this.setData({
                            imgSrc: res.path,
                        });
                    }
                    // 计算最后图片尺寸
                    this._imgComputeSize();
                    this._draw();
                },
            });
        },

        /**
         * 监听器
         */
        _watcher() {
            Object.keys(this.data).forEach((v) => {
                console.log("_watcher__遍历监控的item:   ", v);

                this._observe(this.data, v, this.data.watch[v]);
            });
        },

        _observe(obj, key, watchFun) {
            var val = obj[key];
            console.log(val, watchFun);

            Object.defineProperty(obj, key, {
                configurable: true,
                enumerable: true,
                set: (value) => {
                    val = value;
                    console.log(
                        key,
                        "   赋值时被监听执行函数",
                        "新值:  ",
                        val,
                        "执行的监听函数:  ",
                        watchFun
                    );

                    watchFun && watchFun(val, this);
                },
                get() {
                    if (
                        val &&
                        "_img_top|img_left||width|height|min_width|max_width|min_height|max_height|export_scale|cut_top|cut_left|canvas_top|canvas_left|img_width|img_height|scale|angle|min_scale|max_scale".indexOf(
                            key
                        ) != -1
                    ) {
                        let ret = parseFloat(parseFloat(val).toFixed(3));
                        if (typeof val == "string" && val.indexOf("%") != -1) {
                            ret += "%";
                        }
                        return ret;
                    }
                    return val;
                },
            });
        },

        _initImageSize() {
            // 处理宽高特殊单位 %>px
            console.log('进入_initImageSize函数', this.data.INIT_IMGWIDTH);
            if (this.data.INIT_IMGWIDTH && typeof this.data.INIT_IMGWIDTH == "string" && this.data.INIT_IMGWIDTH.indexOf("%") != -1) {
                let width = this.data.INIT_IMGWIDTH.replace("%", "");
                this.data.INIT_IMGWIDTH = this.data.img_width = this.data.info.windowWidth / 100 * width;
            }
            if (this.data.INIT_IMGHEIGHT && typeof this.data.INIT_IMGHEIGHT == "string" && this.data.INIT_IMGHEIGHT.indexOf("%") != -1) {
                let height = this.data.img_height.replace("%", "");
                this.data.INIT_IMGHEIGHT = this.data.img_height = this.data.info.windowHeight / 100 * height;
            }
        },

        /**
         * 计算图片尺寸
         */
        _imgComputeSize() {
            let img_width = this.data.img_width,
                img_height = this.data.img_height;
            if (!this.data.INIT_IMGHEIGHT && !this.data.INIT_IMGWIDTH) {
                // 258 258
                img_width = this.data.imageObject.width;
                img_height = this.data.imageObject.height;

                console.log(this.data.width, this.data.height);

                if (img_width / img_height > this.data.width / this.data.height) {
                    img_height = this.data.height;
                    img_width =
                        (this.data.imageObject.width / this.data.imageObject.height) *
                        img_height;
                } else {
                    img_width = this.data.width;
                    img_height =
                        (this.data.imageObject.height / this.data.imageObject.width) *
                        img_width;
                }
            }
            this.setData({
                img_width: img_width,
                img_height: img_height,
            });
        },

        _initCanvas() {
            // 初始化canvas
            if (!this.data.ctx) {
                this.data.ctx = wx.createCanvasContext("image-cropper", this);
            }
        },

        _draw(callback) {
            if (!this.data.imgSrc) return;
            console.log(this.data.imgSrc);
        },
        /**
         * 检测剪裁框位置是否在允许的范围内(屏幕内)
         */
        _cutDetectionPosition() {
            let _cutDetectionPositionTop = () => {
                    //检测上边距是否在范围内
                    if (this.data.cut_top < 0) {
                        this.setData({
                            cut_top: 0,
                        });
                    }
                    if (
                        this.data.cut_top >
                        this.data.info.windowHeight - this.data.height
                    ) {
                        this.setData({
                            cut_top: this.data.info.windowHeight - this.data.height,
                        });
                    }
                },
                _cutDetectionPositionLeft = () => {
                    //检测左边距是否在范围内
                    if (this.data.cut_left < 0) {
                        this.setData({
                            cut_left: 0,
                        });
                    }
                    if (
                        this.data.cut_left >
                        this.data.info.windowWidth - this.data.width
                    ) {
                        this.setData({
                            cut_left: this.data.info.windowWidth - this.data.width,
                        });
                    }
                };
            //裁剪框坐标处理（如果只写一个参数则另一个默认为0，都不写默认居中）
            if (this.data.cut_top == null && this.data.cut_left == null) {
                console.log("cut_top, cut_left为空执行函数_setCutCenter()");

                this._setCutCenter();
            } else if (this.data.cut_top != null && this.data.cut_left != null) {
                _cutDetectionPositionTop();
                _cutDetectionPositionLeft();
            } else if (this.data.cut_top != null && this.data.cut_left == null) {
                _cutDetectionPositionTop();
                this.setData({
                    cut_left: (this.data.info.windowWidth - this.data.width) / 2,
                });
            } else if (this.data.cut_top == null && this.data.cut_left != null) {
                _cutDetectionPositionLeft();
                this.setData({
                    cut_top: (this.data.info.windowHeight - this.data.height) / 2,
                });
            }
        },

        _setCutCenter() {
            let cut_top = (this.data.info.windowHeight - this.data.height) * 0.5;
            let cut_left = (this.data.info.windowWidth - this.data.width) * 0.5;
            this.setData({
                cut_top: cut_top, //截取的框上边距
                cut_left: cut_left, //截取的框左边距
            });
        },

        //改变截取框大小
        _computeCutSize() {
            console.log(
                "_computeCutSize函数中width+cut_left: ",
                this.data.width,
                "+",
                this.data.cut_left,
                "=",
                this.data.width + this.data.cut_left
            );
            if (this.data.width > this.data.info.windowWidth) {
                this.setData({
                    width: this.data.info.windowWidth,
                });
            } else if (
                this.data.width + this.data.cut_left >
                this.data.info.windowWidth
            ) {
                this.setData({
                    cut_left: this.data.info.windowWidth - this.data.cut_left,
                });
            }
            if (this.data.height > this.data.info.windowHeight) {
                this.setData({
                    height: this.data.info.windowHeight,
                });
            } else if (
                this.data.height + this.data.cut_top >
                this.data.info.windowHeight
            ) {
                this.setData({
                    cut_top: this.data.info.windowHeight - this.data.cut_top,
                });
            }!this.data._canvas_overflow && this._draw();
        },
    },
});